/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.table;

import com.alibaba.fastjson2.JSONArray;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.table.ColumnType;
import com.je.common.base.entity.extjs.DbModel;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.metadata.IdType;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.service.table.MetaTableService;
import com.je.table.vo.TableDataView;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RpcSchema(schemaId = "metaTableRpcService")
public class MetaTableRpcServiceImpl implements MetaTableRpcService {

    @Autowired
    private MetaTableService metaTableService;
    @Autowired
    private MetaService metaService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DynaCache dynaCache;

    @Override
    public boolean createTable(String resourceTableId) {
        throw new RuntimeException("不应该通过RPC方式调用此方法！");
    }

    @Override
    public DynaBean changePrimaryKeyPolicy(String resourceId, String tableCode, String type, String incrementerName, String generatorSql) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
        if (dynaBean == null) {
            return null;
        }
        dynaBean.set("RESOURCETABLE_KEY_GENERATOR_TYPE", type);
        dynaBean.set("RESOURCETABLE_INCREMENTER_NAME", incrementerName);
        dynaBean.set("RESOURCETABLE_KEY_GENERATOR_SQL", generatorSql);
        metaService.update(dynaBean);
        DynaBean column = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", resourceId).eq("TABLECOLUMN_TYPE", "ID"));
        //如果是NONE，将主键字段类型改为varchar(50)
        if (IdType.getIdType(type) == IdType.NONE) {
            if (column != null) {
                column.setStr("TABLECOLUMN_TYPE", "VARCHAR50");
            }
            metaService.update(column);
        }
        //如果是UUID、AUTO、AUTO_INCREMENTER、SQL，将主键字段类型改为varchar(50)
        if (IdType.getIdType(type) == IdType.AUTO ||
                IdType.getIdType(type) == IdType.AUTO_INCREMENTER || IdType.getIdType(type) == IdType.SQL) {
            if (column != null) {
                column.setStr("TABLECOLUMN_TYPE", ColumnType.CUSTOMID);
                column.setStr("TABLECOLUMN_LENGTH", "bigint(20)");
            }
            metaService.update(column);
        }
        clearTableCache(tableCode);
        return dynaBean;
    }

    @Override
    public List<String> clearTableCache(String tableCode) {
        List<String> resultTableCodes = new ArrayList<>();
        List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", tableCode));
        if (list.size() > 0) {
            DynaBean dynaBean = list.get(0);
            StringBuffer resultStr = new StringBuffer();
            getTableCodeByViewTableId(resultStr, dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
            resultTableCodes = Arrays.asList(resultStr.toString().split(","));
        }
        for (String itCode : resultTableCodes) {
            tableCache.removeCache(itCode);
            dynaCache.removeCache(itCode);
        }
        return resultTableCodes;
    }

    private void getTableCodeByViewTableId(StringBuffer resultStr, String id) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", id);
        if (dynaBean == null) {
            return;
        }
        if (resultStr.length() > 0) {
            resultStr.append(",");
        }
        resultStr.append(dynaBean.getStr("RESOURCETABLE_TABLECODE"));
        String tablesId = dynaBean.getStr("RESOURCETABLE_TABLESINFO");
        if (!Strings.isNullOrEmpty(tablesId)) {
            String[] bTablesId = tablesId.split(",");
            for (String tableId : bTablesId) {
                if (!Strings.isNullOrEmpty(tableId)) {
                    getTableCodeByViewTableId(resultStr, tableId);
                }
            }
        }
    }

    @Override
    public List<String> generateChangeTablePrimaryKeyDDL(String tableCode, String oldPk, String newPK) {
        return metaTableService.generateChangeTablePrimaryKeyDDL(tableCode, oldPk, newPK);
    }

    @Override
    public List<DynaBean> findTableNames(List<String> idList) {
        return metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().in("JE_CORE_RESOURCETABLE_ID", idList));
    }

    @Override
    public List<String> generateCreateDDL(String resourceTableId) {

        return metaTableService.generateCreateDDL(resourceTableId);
    }

    @Override
    public DynaBean afterTableCreated(String resourceTableId) {
        return metaTableService.afterTableCreated(resourceTableId);
    }

    @Override
    public List<String> generateUpdateDDL(String resourceTableId, List<DbModel> dbModels) {
        return metaTableService.generateUpdateDDL(resourceTableId, dbModels);
    }

    @Override
    public void afterTableUpdated(String resourceTableId) {
        metaTableService.afterTableUpdated(resourceTableId);
    }

    @Override
    public List<String> generateRemoveDDL(String ids) {
        return metaTableService.generateRemoveDDL(ids);
    }

    @Override
    public DynaBean impTable(DynaBean resourceTable) {
        return metaTableService.impTable(resourceTable);
    }

    @Override
    public DynaBean syncTable(DynaBean table, List<DbModel> dbModels, boolean isDdl) {
        return metaTableService.syncTable(table, dbModels, isDdl);
    }

    @Override
    public boolean updateTable(String resourceTableId, Boolean isFuncs) {
        return metaTableService.updateTable(resourceTableId, isFuncs);
    }

    @Override
    public boolean updateFunTable(String resourceTableId) {
        return metaTableService.updateTable(resourceTableId, true);
    }

    @Override
    public void syncTreePath(String tableCode, String pkCode, String preFix) {
        metaTableService.syncTreePath(tableCode, pkCode, preFix);
    }

    @Override
    public List<Map<String, Object>> selectSqlTable(JSONArray columnList, JSONArray whereList, JSONArray orderList, String tableCode, String page) {
        return metaTableService.selectSqlTable(columnList, whereList, orderList, tableCode, page);
    }

    @Override
    public List<String> generateInsertSQL(JSONArray columnList, List<Map<String, Object>> list, String tableCode, boolean status) {
        return metaTableService.generateInsertSQL(columnList, list, tableCode, status);
    }

    @Override
    public List<TableDataView> selectParentTable(DynaBean infoById) {
        return metaTableService.selectParentTable(infoById);
    }

    @Override
    public List<TableDataView> selectChildTable(DynaBean infoById) {
        return metaTableService.selectChildTable(infoById);
    }

    @Override
    public List<TableDataView> selectTableByView(DynaBean dynaBean) {
        return metaTableService.selectTableByView(dynaBean);
    }

    @Override
    public List<TableDataView> selectTableByFunc(DynaBean infoById) {
        return metaTableService.selectTableByFunc(infoById);
    }

    @Override
    public List<TableDataView> selectTableByMenus(List<String> list) {
        return metaTableService.selectTableByMenus(list);
    }

    @Override
    public DynaBean doSave(DynaBean dynaBean) {
        return metaTableService.doSave(dynaBean);
    }

    @Override
    public DynaBean pasteTable(String newTableName, String newTableCode, DynaBean dynaBean, String useNewName) {
        return metaTableService.pasteTable(newTableName, newTableCode, dynaBean, useNewName);
    }

    @Override
    public DynaBean doUpdate(DynaBean dynaBean) {
        return metaTableService.doUpdate(dynaBean);
    }

    @Override
    public DynaBean move(String resourceId, String toResourceId, String place) {
        return metaTableService.move(resourceId, toResourceId, place);
    }

    @Override
    public String getTableType(String parentId) {
        return metaTableService.getTableType(parentId);
    }

    @Override
    public DynaBean selectRelation(String pkValue) {
        return metaTableService.selectRelation(pkValue);
    }

    @Override
    public List<Map<String, Object>> loadHistoricalTraces(String resourceId) {
        return metaTableService.loadHistoricalTraces(resourceId);
    }

    @Override
    public void syncTableField(String pkValue, String ckPkValue) {
        metaTableService.syncTableField(pkValue, ckPkValue);
    }

    @Override
    public String changeTablePrimaryKey(String pkValue, String newCode) throws APIWarnException {
        return null;
    }


    @Override
    public DynaBean selectOneByPk(String resourceTable, String resourceId) {
        return metaTableService.selectOneByPk(resourceTable, resourceId);
    }

    @Override
    public void removeTableMetaToMetaNoDDL(String ids) {
        metaTableService.deleteTableMeta(ids);
    }

    @Override
    public DynaBean selectOneByCodeToType(String tableCode) {
        return metaTableService.selectOneByCodeToType(tableCode);
    }

    @Override
    public List<DynaBean> selectTableByResourceTablePk(String tableCode, String resourcetableId) {
        return metaTableService.selectTableByResourceTablePk(tableCode, resourcetableId);
    }

    @Override
    public List<DynaBean> selectTableInIds(String tableCode, String tablecolumnId, String[] ids) {
        return metaTableService.selectTableInIds(tableCode, tablecolumnId, ids);
    }

    @Override
    public List<DynaBean> selectColmListInIds(String tablecolumnId) {
        return metaTableService.selectColmListInIds(tablecolumnId);
    }

    @Override
    public Boolean checkTableCodeExcludeCode(DynaBean table) {
        return metaTableService.checkTableCodeExcludeCode(table);
    }

    @Override
    public String getDeleteTableDDlByIds(String ids) {
        return metaTableService.getDeleteTableDDlByIds(ids);
    }


    @Override
    public String checkBeforeDeletion(String ids) {
        return metaTableService.deleteCheck(ids);
    }

    @Override
    public DynaBean afterImportMetaInfo(DynaBean table, List<Map<String, Object>> lists) {
        return metaTableService.afterImportMetaInfo(table, lists);
    }

    @Override
    public DynaBean beforeImportBuildDynabeanInfo(DynaBean table) {
        return metaTableService.beforeImportBuildDynabeanInfo(table);
    }

    @Override
    public List<DynaBean> selectByColumnCode(String tableCode) {
        return metaTableService.selectByColumnCode(tableCode);
    }

    @Override
    public String checkTableForApply(String tableId) {
        return metaTableService.checkTableForApply(tableId);
    }

}
